package com.cinc.ebc.mm.controller;

import com.alibaba.druid.support.json.JSONUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cinc.ebc.mm.entity.MmStockInit;
import com.cinc.ebc.mm.entity.MmStockInitDetail;
import com.cinc.ebc.mm.model.MmStockInitDetailModel;
import com.cinc.ebc.mm.model.template.MmStockInitImpTemplate;
import com.cinc.ebc.mm.service.IMmStockInitDetailService;
import com.cinc.ebc.mm.service.IMmStockInitService;
import com.cinc.ebc.mm.util.ExcelVerifyHandlerUtil;
import com.cinc.ebc.mm.vo.MmStockInitDetailPage;
import com.cinc.ebc.mm.vo.MmStockInitPage;
import io.micrometer.core.instrument.util.JsonUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.config.AutoPoiDictConfig;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.annotation.Excel;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.result.ExcelImportResult;
import org.jeecgframework.poi.excel.entity.result.ExcelVerifyHanlderResult;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecgframework.poi.handler.inter.IExcelVerifyHandler;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: 库存初始化
 * @Author: jeecg-boot
 * @Date: 2022-07-03
 * @Version: V1.0
 */
@Api(tags = "库存初始化")
@RestController
@RequestMapping("/mm/stockInit")
@Slf4j
public class MmStockInitController {
    @Autowired
    private IMmStockInitService mmStockInitService;
    @Autowired
    private IMmStockInitDetailService mmStockInitDetailService;

    /**
     * 分页列表查询
     *
     * @param mmStockInit
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "库存初始化-分页列表查询")
    @ApiOperation(value = "库存初始化-分页列表查询", notes = "库存初始化-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(MmStockInit mmStockInit,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<MmStockInit> queryWrapper = QueryGenerator.initQueryWrapper(mmStockInit, req.getParameterMap());
        Page<MmStockInit> page = new Page<MmStockInit>(pageNo, pageSize);
        IPage<MmStockInit> pageList = mmStockInitService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 明细分页查询
     *
     * @param detailPage
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @PermissionData(pageComponent = "ebc/mm/MmStockInitDetailList")
    @AutoLog(value = "库存初始化明细-分页列表查询")
    @ApiOperation(value = "库存初始化明细-分页列表查询", notes = "库存初始化明细-分页列表查询")
    @GetMapping(value = "/detailPageList")
    public Result<?> queryDetailPageList(MmStockInitDetailPage detailPage,
                                         @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                         @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                         HttpServletRequest req) {
        Page<MmStockInitDetailModel> page = new Page<>(pageNo, pageSize);
        mmStockInitService.detaiPage(page, detailPage);
        return Result.OK(page);
    }

    /**
     * 明细列表查询
     *
     * @param detailPage
     * @return
     */
    @PermissionData(pageComponent = "ebc/mm/MmStockInitDetailList")
    @AutoLog(value = "库存初始化明细-分页查询")
    @ApiOperation(value = "库存初始化明细-分页查询", notes = "库存初始化明细-分页查询")
    @GetMapping(value = "/detailList")
    public Result<?> queryDetailList(MmStockInitDetailPage detailPage) {
        List<MmStockInitDetailModel> dataList = mmStockInitService.detailList(detailPage);
        return Result.OK(dataList);
    }

    /**
     * 添加
     *
     * @param mmStockInitPage
     * @return
     */
    @AutoLog(value = "库存初始化-添加")
    @ApiOperation(value = "库存初始化-添加", notes = "库存初始化-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody MmStockInitPage mmStockInitPage) {
        MmStockInit mmStockInit = new MmStockInit();
        BeanUtils.copyProperties(mmStockInitPage, mmStockInit);
        mmStockInitService.saveMain(mmStockInit, mmStockInitPage.getMmStockInitDetailList());
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param mmStockInitPage
     * @return
     */
    @AutoLog(value = "库存初始化-编辑")
    @ApiOperation(value = "库存初始化-编辑", notes = "库存初始化-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody MmStockInitPage mmStockInitPage) {
        MmStockInit mmStockInit = new MmStockInit();
        BeanUtils.copyProperties(mmStockInitPage, mmStockInit);
        MmStockInit mmStockInitEntity = mmStockInitService.getById(mmStockInit.getId());
        if (mmStockInitEntity == null) {
            return Result.error("未找到对应数据");
        }
        mmStockInitService.updateMain(mmStockInit, mmStockInitPage.getMmStockInitDetailList());
        return Result.OK("编辑成功!");
    }

    /**
     *  初始化
     *
     * @param detailPageList
     * @return
     */
    @AutoLog(value = "初始化")
    @ApiOperation(value="初始化", notes="初始化")
    @PostMapping(value = "/handleInit")
    public Result<?> handleInit(@RequestBody List<MmStockInitDetailPage> detailPageList) throws Exception {
        mmStockInitService.handleInit(detailPageList);
        return Result.OK("初始化成功！");
    }

    /**
     *  单据冲销
     *
     * @param detailPageList
     * @return
     */
    @AutoLog(value = "单据冲销")
    @ApiOperation(value="单据冲销", notes="单据冲销")
    @PostMapping(value = "/writeOff")
    public Result<?> writeOff(@RequestBody List<MmStockInitDetailPage> detailPageList) throws Exception {
        mmStockInitService.writeOff(detailPageList);
        return Result.OK("冲销成功！");
    }

    /**
     *   通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "库存初始化明细-通过id删除")
    @ApiOperation(value="库存初始化明细-通过id删除", notes="库存初始化明细-通过id删除")
    @DeleteMapping(value = "/deleteDetail")
    public Result<?> deleteDetail(@RequestParam(name="id",required=true) String id) throws Exception {
        mmStockInitService.delDetail(id);
        return Result.OK("删除成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "库存初始化-通过id删除")
    @ApiOperation(value = "库存初始化-通过id删除", notes = "库存初始化-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        mmStockInitService.delMain(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "库存初始化-批量删除")
    @ApiOperation(value = "库存初始化-批量删除", notes = "库存初始化-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.mmStockInitService.delBatchMain(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "库存初始化-通过id查询")
    @ApiOperation(value = "库存初始化-通过id查询", notes = "库存初始化-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        MmStockInit mmStockInit = mmStockInitService.getById(id);
        if (mmStockInit == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(mmStockInit);

    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "库存初始化明细通过主表ID查询")
    @ApiOperation(value = "库存初始化明细主表ID查询", notes = "库存初始化明细-通主表ID查询")
    @GetMapping(value = "/queryMmStockInitDetailByMainId")
    public Result<?> queryMmStockInitDetailListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<MmStockInitDetail> mmStockInitDetailList = mmStockInitDetailService.selectByMainId(id);
        return Result.OK(mmStockInitDetailList);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param mmStockInit
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, MmStockInit mmStockInit) {
        // Step.1 组装查询条件查询数据
        QueryWrapper<MmStockInit> queryWrapper = QueryGenerator.initQueryWrapper(mmStockInit, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        //Step.2 获取导出数据
        List<MmStockInit> queryList = mmStockInitService.list(queryWrapper);
        // 过滤选中数据
        String selections = request.getParameter("selections");
        List<MmStockInit> mmStockInitList = new ArrayList<MmStockInit>();
        if (oConvertUtils.isEmpty(selections)) {
            mmStockInitList = queryList;
        } else {
            List<String> selectionList = Arrays.asList(selections.split(","));
            mmStockInitList = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
        }

        // Step.3 组装pageList
        List<MmStockInitPage> pageList = new ArrayList<MmStockInitPage>();
        for (MmStockInit main : mmStockInitList) {
            MmStockInitPage vo = new MmStockInitPage();
            BeanUtils.copyProperties(main, vo);
            List<MmStockInitDetail> mmStockInitDetailList = mmStockInitDetailService.selectByMainId(main.getId());
            vo.setMmStockInitDetailList(mmStockInitDetailList);
            pageList.add(vo);
        }

        // Step.4 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "库存初始化列表");
        mv.addObject(NormalExcelConstants.CLASS, MmStockInitPage.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("库存初始化数据", "导出人:" + sysUser.getRealname(), "库存初始化"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 下载excel导入模板
     *
     * @param request
     */
    @RequestMapping(value = "/downloadXlsTemplate")
    public ModelAndView downloadXlsTemplate(HttpServletRequest request) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "库存初始化导入模板");
        mv.addObject(NormalExcelConstants.CLASS, MmStockInitImpTemplate.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("库存初始化数据", "导入人:" + sysUser.getRealname(), "库存初始化"));
        mv.addObject(NormalExcelConstants.DATA_LIST, new ArrayList<>());
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            //获取导入校验器
            final int[] countObj = {4};
            List<String> fieldNameList = new ArrayList<>();
            List<String> excelNameList = new ArrayList<>();
            Arrays.stream(MmStockInitImpTemplate.class.getDeclaredFields()).forEach(field -> {
                if(field.getAnnotation(Excel.class) != null){
                    fieldNameList.add(field.getName());
                    excelNameList.add(field.getAnnotation(Excel.class).name());
                }
            });
            IExcelVerifyHandler excelVerifyHandler = ExcelVerifyHandlerUtil.getExcelVerifyHandlerBase(countObj, fieldNameList, excelNameList);
            params.setVerifyHanlder(excelVerifyHandler);
            try {
                ExcelImportResult<MmStockInitPage> importResult = ExcelImportUtil.importExcelVerify(file.getInputStream(), MmStockInitPage.class, params);
                List<MmStockInitPage> list = importResult.getList();
                for (MmStockInitPage page : list) {
                    MmStockInit po = new MmStockInit();
                    BeanUtils.copyProperties(page, po);
//                    mmStockInitService.saveMain(po, page.getMmStockInitDetailList());
                }
                return Result.OK("文件导入成功！数据行数:" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.OK("文件导入失败！");
    }

}
